import $config from '@/config';
import $sr from '@/utils/x-sr';
import $http from '@/utils/x-request';

export default {
  namespaced: true,
  state: {
    SubscribeMessageInfo: null, // 订阅消息详情
    userInfo: null,
    token: null,
    retryCount: 1
  },
  mutations: {
    SET_DATA: (state, data) => {
      for (const key in data) {
        state[key] = data[key];
      }
    }
  },
  actions: {
    setData({ commit }, data) {
      return new Promise((resolve, reject) => {
        commit('SET_DATA', data);
        resolve();
      });
    },
    login({ commit, dispatch }, options) {
      return new Promise(async(resolve, reject) => {
        const userInfo = uni.getStorageSync($config.userInfoName) || {};
        const token = uni.getStorageSync($config.tokenName);
        const time = new Date();
        // token 7天有效
        let timeout = false;
        try {
          if (userInfo && userInfo.createTime) {
            timeout = userInfo.createTime ? time - userInfo.createTime > (86400000 * 7) : false;
          }
        } catch (e) {
          console.warn('校验token当天有效error');
        }

        // 有token并且有用户信息并且没超时并且不需要强制获取，forcibly强制授权
        if (token && userInfo && !timeout && !options?.forcibly) {
          commit('SET_DATA', {
            token,
            userInfo: userInfo
          });
          resolve({
            ...userInfo,
            accessToken: token
          });
        } else {
          console.log(options?.api);
          dispatch('getToken').then((res) => {
            resolve(res);
          });
        }
      });
    },
    // 获取有效的token
    getToken({ commit, dispatch, state }) {
      return new Promise((resolve, reject) => {
        try {
          wx.login({
            success: (response) => {
              $http({
                method: 'post',
                url: '/account/user/iu/oauth/login',
                data: {
                  code: response.code
                },
                // 静默授权接口单独设置5秒超时
                timeout: 5000,
                alarm: true,
                error: false,
                report: false
              }).then(res => {
                const data = res.data;
                data.createTime = +new Date();

                // 如果缓存中已经有手机号了，那么使用缓存中的手机号，避免被覆盖
                if (!data.accountMobile && state.userInfo?.accountMobile) {
                  data.accountMobile = state.userInfo?.accountMobile;
                }
                // 存储到本地缓存
                uni.setStorageSync($config.tokenName, data.accessToken);
                uni.setStorageSync($config.userInfoName, data);
                commit('SET_DATA', {
                  token: data.accessToken,
                  userInfo: data,
                  retryCount: 1
                });

                // 更正有数数据
                $sr.setUser(data);
                resolve(data);
              }).catch(() => {
                // console.warn('oauth/login->', err);
                // 错误就重试，直到成功为止
                setTimeout(() => {
                  commit('SET_DATA', {
                    retryCount: state.retryCount + 1
                  });
                  dispatch('getToken').then((res) => {
                    resolve(res);
                  });
                }, state.retryCount * 200);
              });
            }
          });
        } catch (e) {
          // console.warn('wx.login->', e, state.retryCount);
          // 错误就重试，直到成功为止
          setTimeout(() => {
            commit('SET_DATA', {
              retryCount: state.retryCount + 1
            });
            dispatch('getToken').then((res) => {
              resolve(res);
            });
          }, state.retryCount * 200);
        }
      });
    },
    // 获取用户信息
    getUserInfo({ dispatch, state }) {
      return new Promise((resolve, reject) => {
        if (state.userInfo?.accountMobile) {
          resolve(state.userInfo);
        } else {
          $http({
            login: true,
            url: '/account/user/info',
            // 静默授权接口单独设置5秒超时
            timeout: 5000,
            alarm: true
          }).then(res => {
            dispatch('updateUserInfo', res.data || {});
            resolve(res.data);
          }).catch(() => {
            reject();
          });
        }
      });
    },
    // 更新用户信息
    updateUserInfo({ commit, state }, options) {
      return new Promise((resolve) => {
        const userInfo = Object.assign(state.userInfo || {}, options);
        uni.setStorageSync($config.userInfoName, userInfo);
        commit('SET_DATA', {
          userInfo
        });
        resolve();
      });
    },
    // 获取官方客服信息
    getCustomerInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        $http({
          url: '/account/customer/service/app/info'
        }).then(res => {
          if (res.data) {
            const { contactWay, corpId } = res.data;
            resolve({
              contactWay,
              corpId
            });
          } else {
            reject();
          }
        });
      });
    }
  }
};
